package com.buding.fx.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuqiyu
 * @ClassName QrCodeUtil
 * @Description 二维码生成
 */
public class QrCodeUtil {

    /**
     * width:图片完整的宽;height:图片完整的高
     */
    private static final int WIDTH = 170;
    /**
     * 二维码图片高度
     */
    private static final int HEIGHT = 170;

    /**
     * @param url 二维码中的地址
     */
    public static ByteArrayOutputStream generateQrcode(String url) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, Comparable> hints = new HashMap<>(16);
            // 设置UTF-8， 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN, 1);
            // 设置二维码的容错性
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 开始画二维码 存放在本地路径
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg", os);
            // 此处将二维码直接上传到了七牛云
            return os;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
